package mcpclient

import (
	"encoding/json"
	"log/slog"
	"os"
)

type StdioConfig map[string]map[string]StdioServerConfig

func (s StdioConfig) Range(f func(string, StdioServerConfig) bool) {
	for key, value := range s["mcpServers"] {
		if !f(key, value) {
			return
		}
	}
}

type StdioServerConfig struct {
	Command string   `json:"command"`
	Args    []string `json:"args"`
	Env     []string `json:"env"`
	Close   bool     `json:"close"`
}

func LoadStdioConfig() (StdioConfig, error) {
	configData, err := os.ReadFile("stdio_config.json")
	if err != nil {
		slog.Error("Failed to read config file", "error", err)
		return nil, err
	}

	var stdioConfig StdioConfig
	err = json.Unmarshal(configData, &stdioConfig)
	if err != nil {
		slog.Error("Failed to parse config file", "error", err)
		return nil, err
	}

	return stdioConfig, nil
}

type SseConfig map[string]map[string]SseServerConfig

type SseServerConfig struct {
	Url    string            `json:"url"`
	Header map[string]string `json:"header"`
}

func (s SseConfig) Range(f func(string, SseServerConfig) bool) {
	for key, value := range s["mcpServers"] {
		if !f(key, value) {
			return
		}
	}
}

func LoadSseConfig() (SseConfig, error) {
	configData, err := os.ReadFile("sse_config.json")
	if err != nil {
		slog.Error("Failed to read config file", "error", err)
		return nil, err
	}
	var sseConfig SseConfig
	err = json.Unmarshal(configData, &sseConfig)
	if err != nil {
		slog.Error("Failed to parse config file", "error", err)
		return nil, err
	}
	return sseConfig, nil
}
